package com.his.his_system.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.his.his_system.common.util.ResultAdvice;
import com.his.his_system.domain.DzmHisAuthPermissions;
import com.his.his_system.service.DzmHisAuthPermissionsService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.List;

@RequestMapping("/his/sys/pems/")
@RestController
@ResponseBody
public class PermissionController {

    @Autowired
    private DzmHisAuthPermissionsService permissionsService;

    @GetMapping("/list")
    public ResultAdvice getPermissionsList() {
        List<DzmHisAuthPermissions> permissionsList =fmtPermission( permissionsService.list());
        return ResultAdvice.success(permissionsList);
    }

    @GetMapping("/{id}")
    public ResultAdvice list(@PathVariable("id") Integer id) {

        List<DzmHisAuthPermissions> list = permissionsService.getCurRole(id);
        return ResultAdvice.success(list);
    }



    //  菜单格式
    private List<DzmHisAuthPermissions> fmtPermission(List<DzmHisAuthPermissions> plist) {
        List<DzmHisAuthPermissions> fatherMenu = new ArrayList<>();

        for (DzmHisAuthPermissions permissions : plist) {
            if (permissions.getFid().equals(0)) {
                fatherMenu.add(permissions);
            }
        }
        for (DzmHisAuthPermissions fm : fatherMenu) {
            List<DzmHisAuthPermissions> allChildrenMenu = getChild(fm.getId().toString(),plist);
            fm.setChildren(allChildrenMenu);
        }

        return fatherMenu;
    }

    //    递归获取子节点
    public List<DzmHisAuthPermissions> getChild(String id, List<DzmHisAuthPermissions> allMenu) {
        //子菜单
        List<DzmHisAuthPermissions> childList = new ArrayList<>();
        for (DzmHisAuthPermissions entity : allMenu) {
            // 遍历所有节点，将所有菜单的父id与传过来的根节点的id比较
            //相等说明：为该根节点的子节点。
            if (entity.getFid().toString().equals(id)) {
                childList.add(entity);
            }
        }
        //递归
        for (DzmHisAuthPermissions entity : childList) {
            entity.setChildren(getChild(entity.getId().toString(), allMenu));
        }
        //Collections.sort(childList,order()); //排序
        //如果节点下没有子节点，返回一个空List（递归退出）
        if (childList.size() == 0) {
            return new ArrayList<>();
        }
        return childList;
    }


}
